<template>
  <div class="content">
    <div class="content-info">
      <div class="form-item">
        <span class="label">告警等级：</span>
        <el-input v-model="formData.alarmLevel" style="width: 200px" disabled />
      </div>
      <div class="form-item">
        <span class="label">告警事项：</span>
        <el-input v-model="eventTypeMap[formData.eventType]" style="width: 200px" disabled />
      </div>
      <div class="form-item">
        <span class="label">告警详情：</span>
        <el-input v-model="formData.alarmContent" style="width: 200px" disabled />
      </div>
      <div class="form-item">
        <span class="label">告警时间：</span>
        <el-input v-model="formData.dateTime" style="width: 200px" disabled />
      </div>
      <div class="form-item">
        <span class="label">告警时环控参数:</span>
        <span>
          温度：{{ formData.temp || '-' }}℃;湿度：{{ formData.humi || '-' }}%;氨气浓度：{{
            formData.ammonia || '-'
          }}ppm
        </span>
      </div>
      <div class="form-item">
        <span class="label">核实情况:</span>
        <el-radio-group v-model="formData.isVerified">
          <el-radio :value="true">有效吿警</el-radio>
          <el-radio :value="false">无效告警</el-radio>
        </el-radio-group>
      </div>
      <div class="form-item" v-if="!formData.isVerified">
        <span class="label">无效原因:</span>
        <el-select v-model="formData.invalidCause" clearable placeholder="请选择">
          <el-option
            v-for="(item, index) in invalidCause"
            :key="index"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </div>
      <div class="form-item" v-if="!formData.isVerified && formData.invalidCause == 3">
        <span class="label">自定义无效原因:</span>
        <el-input
          v-model="formData.invalidReason"
          style="width: 200px"
          placeholder="请输入无效原因"
        />
      </div>
      <div class="form-item">
        <span class="label">巡查项:</span>
        <el-select
          v-model="formData.patrolItem"
          clearable
          placeholder="请选择"
          @change="changePatrolItem"
          :disabled="!!formData.notStandardNo"
        >
          <el-option
            v-for="(item, index) in patrolItemOption"
            :key="index"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </div>
      <div class="form-item">
        <span class="label">巡查点:</span>
        <el-select
          v-model="formData.patrolSpot"
          clearable
          placeholder="请选择"
          :disabled="!!formData.notStandardNo"
        >
          <el-option
            v-for="(item, index) in patrolSpotOption"
            :key="index"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </div>
      <div class="form-item">
        <span class="label">巡查条件:</span>
        <el-select
          v-model="formData.patrolConditions"
          clearable
          placeholder="请选择"
          :disabled="!!formData.notStandardNo"
        >
          <el-option
            v-for="(item, index) in patrolSpotOption"
            :key="index"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </div>
      <div class="form-item">
        <span class="label">巡查值:</span>
        <el-input v-model="formData.patrolValu" style="width: 200px" placeholder="请输入">
          <template #append>%</template>
        </el-input>
      </div>
      <div class="form-item">
        <span class="label">巡查异常值:</span>
        <el-input v-model="formData.coverRatio" style="width: 200px" placeholder="请输入">
          <template #append>%</template>
        </el-input>
      </div>
      <div class="form-item" v-if="formData.patrolItem === '3'">
        <span class="label">饲喂形态:</span>
        <el-select v-model="feedType" clearable placeholder="请选择">
          <el-option
            v-for="(item, index) in feedTypeOption"
            :key="index"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </div>
      <div class="form-item" v-if="formData.patrolItem === '3'">
        <span class="label">病弱猪类型:</span>
        <el-select v-model="illType" clearable placeholder="请选择">
          <el-option
            v-for="(item, index) in illTypeOption"
            :key="index"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </div>
      <div class="form-item">
        <span class="label">整改截止日期:</span>
        <el-date-picker
          v-model="formData.correctionDate"
          type="datetime"
          placeholder="请选择"
          format="YYYY-MM-DD HH:mm:ss"
          date-format="MMM DD, YYYY"
          time-format="HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
          :disabled-date="disabledDate"
        />
      </div>
      <div class="form-item">
        <span class="label">是否集中运营:</span>
        <el-radio-group v-model="formData.focusOperation">
          <el-radio :value="true">是</el-radio>
          <el-radio :value="false">否</el-radio>
        </el-radio-group>
      </div>
    </div>
    <div class="form-item">
      <span class="label">备注:</span>
      <span>
        <el-input
          v-model="formData.notes"
          style="width: 1000px"
          placeholder="请输入"
          type="textarea"
        />
      </span>
    </div>
    <div class="line"></div>
    <div class="content-media">
      <div class="content-media-left">
        <div class="form-video">
          <span class="label">告警视频</span>
          <div class="btn-group">
            <el-button
              :icon="Crop"
              type="primary"
              @click="catchPic"
              style="width: 100px"
              :loading="catchPicLoading"
              >抓图</el-button
            >
            <!-- <el-button type="primary" @click="showVideo">打开页面</el-button> -->
            <!-- <el-button type="primary" @click="changeVisible">显示/隐藏</el-button> -->
          </div>
          <div class="btn-group">
            <el-button v-for="(item, index) in list" :key="index" @click="clickItem(index)">
              {{ item.text }}
            </el-button>
          </div>
          <div class="video">
            <iframe
              class="video"
              ref="myIframe"
              width="95%"
              height="600px"
              v-if="props.isShowIframe"
            ></iframe>
          </div>
        </div>
      </div>
      <div class="content-media-right">
        <div class="form-image">
          <span class="label">告警图片</span>
          <div class="imageBox">
            <div class="imageBox-item" v-for="(item, index) in picList" :key="index">
              <el-image
                style="width: 100px; height: 100px"
                :src="item"
                :zoom-rate="1.2"
                :max-scale="7"
                :min-scale="0.2"
                :preview-src-list="picList"
                show-progress
                :initial-index="4"
                fit="cover"
                @show="changeVisible(false)"
                @close="changeVisible(true)"
              >
              </el-image>
              <el-button
                type="danger"
                class="delete"
                :icon="Delete"
                circle
                @click="deletePic(index)"
              />
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="content-button">
      <div class="form-button">
        <el-button type="primary" @click="reset">重置 </el-button>
        <el-button
          type="primary"
          :disabled="!hasPermission || formData.alarmState == '2'"
          :loading="saveLoading"
          @click="save"
          >确认提交
        </el-button>
      </div>
    </div>
  </div>
</template>
<script setup>
import { onMounted, ref, watch } from 'vue'
import {
  getPatrolAlarmDetailInfo,
  savePatrolAlarmDetails,
  getRolePermissions,
  uploadImage
} from '@/api/api'
import { useRoute } from 'vue-router'
import { Crop, Delete } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

const route = useRoute()
const formData = ref({})
const cacheFormData = ref({})
const saveLoading = ref(false)

const props = defineProps({
  isShowIframe: {
    type: Boolean,
    default: true
  },
  fid: {
    type: String,
    default: ''
  }
})

const eventTypeMap = {
  1: '空栏巡查',
  2: '饲养',
  3: '生物资产端到端',
  4: '生物安全',
  5: '健康',
  6: '上市巡查'
}
const patrolItemOption = [
  { label: '肉猪空栏洗消', value: '1' },
  { label: '肉猪分栏', value: '2' },
  { label: '肉猪健康-差弱猪护理', value: '3' },
  { label: '肉猪生长监测', value: '4' },
  { label: '生物资产端到端-进苗验收', value: '5' },
  { label: '生物安全-红区管理', value: '6' },
  { label: '生物资产端到端-死淘申报', value: '7' },
  { label: '肉猪饲喂', value: '8' },
  { label: '肉猪环控', value: '9' },
  { label: '生物资产端到端-过程盘点', value: '10' },
  { label: '生物资产端到端-上市盘点', value: '11' },
  { label: '生物资产端到端-上市尾猪处理', value: '12' }
]

const disabledDate = (time) => {
  return time.getTime() < Date.now() - 8.64e7
}

// 抓取视频
const list = ref([])
const myIframe = ref(null)
const showVideo = () => {
  let rect = myIframe.value.getBoundingClientRect()
  // 大华 测试调用需要加上 &access_token=xxx ，正式：https://cq.wens.com.cn//isv/wens/smartb/smartbAiVideo/base.html#/
  myIframe.value.src = `https://t-mall.wens.com.cn//isv/wens/smartb/smartbAiVideo/base.html#/DigtalSpaceVideoPlayerForIframe?orgId=${route.query.orgId}&farmerId=${formData.value.cqRearerId}&iframeFixLeftOffset=${rect.left + window.scrollX}&iframeFixTopOffset=${rect.top + window.scrollY}`
  // `http://10.33.63.26:8089/isv/wens/smartb/smartbAiVideo/base.html#/DigtalSpaceVideoPlayerForIframe?orgId=621045996649978880&farmerId=2576887123550956095&access_token=1554963617547709203_O6k5d3eKqpkXU3aE32BFH0SbqdT5WDOdLaEfkSaROFPUre248LmGvOJmwJxJW8yW6wkheY0vqYGnnYyq3EMt8aI5oW2Gp3YcCX1d`
  console.log('视频src', myIframe.value.src)
  // 海康
  // let rect = this.$refs.myIframe.getBoundingClientRect()
  // this.$refs.myIframe.src =
  //   'http://127.0.0.1:8089/isv/wens/smartb/smartbAiVideo/base.html#/DigtalSpaceVideoPlayerForIframe?orgId=621045942434400257&farmerId=2767005205788511979&iframeFixLeftOffset=' +
  //   (rect.left + window.scrollX) +
  //   '&iframeFixTopOffset=' +
  //   (rect.top + window.scrollY)
}

// 生成当前时间
const getCurrentDate = () => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')

  const formattedDate = `${year}-${month}-${day}`
  console.log(formattedDate)
  return formattedDate
}

const catchPicLoading = ref(false)
const catchPic = () => {
  if (picList.value.length == 3) {
    ElMessage({
      message: '最多抓取3张图片',
      type: 'warning'
    })
    return
  }
  catchPicLoading.value = true
  myIframe.value.contentWindow.postMessage(
    {
      handle: 'catchPic'
    },
    '*'
  )
}

const deletePic = (index) => {
  picList.value.splice(index, 1)
}

const changeVisible = (flag) => {
  console.log('changeVisible', flag)
  myIframe.value.contentWindow.postMessage(
    {
      handle: 'changeVisible',
      data: flag
    },
    '*'
  )
}

const clickItem = (index) => {
  // 打开对应视频
  myIframe.value.contentWindow.postMessage(
    {
      handle: 'playVideo',
      data: index
    },
    '*'
  )
}

// 巡查点选项
const patrolSpotOption = ref([])
watch(
  () => formData.value.patrolItem,
  (newVal) => {
    // 根据 newVal 的值选择对应的 patrolSpotOption
    switch (newVal) {
      case '1': // 肉猪空栏洗消
        patrolSpotOption.value = [
          { label: '巡查员远程验收是否达标', value: '14' },
          { label: '环境采样是否阳性', value: '15' }
        ]
        break
      case '4': // 肉猪生长监测
        patrolSpotOption.value = [
          { label: '实际测算猪群单头体重低于对应生长天龄目标体重(斤)', value: '1' },
          { label: '实际测算猪群单头体重低于对应累计耗料目标体重(斤)', value: '2' },
          { label: '实际日增重偏高标准日增重(斤)', value: '3' },
          { label: '累计耗料量偏离标准耗料(%)', value: '4' }
        ]
        break
      case '5': // 生物资产端到端-进苗验收
        patrolSpotOption.value = [{ label: 'AI点数记录与仔猪上市记录数差异头数', value: '16' }]
        break
      case '6': // 生物安全-红区管理
        patrolSpotOption.value = [
          { label: '是否存在对应人员、物资的进出报备单记录', value: '20' },
          { label: '智能烘干消毒是否正常结束', value: '21' },
          { label: '智能浸泡消毒是否正常结束', value: '22' }
        ]
        break
      case '8': // 肉猪饲喂
        patrolSpotOption.value = [
          { label: '料槽余料覆盖率(%)', value: '5' },
          { label: '料槽余料异常占比(%)', value: '6' }
        ]
        break
      case '9': // 肉猪环控
        patrolSpotOption.value = [
          { label: '温度', value: '7' },
          { label: '湿度', value: '8' },
          { label: 'CO2', value: '9' },
          { label: '智能环控舒适度(待建)', value: '10' },
          { label: '猪群打堆比例', value: '11' },
          { label: '猪群集中在排泄区数量', value: '12' },
          { label: '猪群异常栏位占比(%)', value: '13' }
        ]
        break
      case '10': // 生物资产端到端-过程盘点
        patrolSpotOption.value = [{ label: 'AI点数记录与系统存栏数差异头数', value: '17' }]
        break
      case '11': // 生物资产端到端-上市盘点
        patrolSpotOption.value = [{ label: 'AI点数记录与肉猪回收单差异头数', value: '18' }]
        break
      case '12': // 生物资产端到端-上市尾猪处理
        patrolSpotOption.value = [{ label: '上市尾猪存栏数(开栏销售标准天数外)', value: '19' }]
        break
      default:
        patrolSpotOption.value = []
    }
  },
  { immediate: true } // 立即执行一次初始化
)

const patrolConditionsOption = [
  { label: 'I级', value: '1' },
  { label: 'II级', value: '2' }
]

const invalidCause = [
  { label: '误识别', value: '1' },
  { label: '设备故障', value: '2' },
  { label: '自定义', value: '3' }
]

const changePatrolItem = () => {
  formData.value.patrolSpot = ''
  formData.value.patrolConditions = ''
}

// watch(
//   () => props.fid,
//   (newVal) => {
//     if (newVal) {
//       fetchPatrolAlarmDetailInfo()
//     }
//   }
// )

// 获取告警详情
const fetchPatrolAlarmDetailInfo = async () => {
  try {
    const res = await getPatrolAlarmDetailInfo({
      fid: route.query.fid
    })
    if (res && res.data) {
      formData.value = res.data
      formData.value.alarmLevel = res.data['alarmLevel'] == 1 ? 'I级' : 'II级'
      formData.value.patrolConditions = res.data['patrolSpot']
      cacheFormData.value = JSON.parse(JSON.stringify(formData.value))
      fetchRolePermissions()
      // 打开视频
      showVideo()
    }
  } catch (error) {
    console.error('获取获取告警详情信息失败:', error)
  }
}

// 任务中心获取派单权限接口
const hasPermission = ref(false)
const fetchRolePermissions = async () => {
  try {
    const res = await getRolePermissions({
      userId: route.query.userId,
      userRole: 'DigitalPatrolAdmin',
      orgId: route.query.orgId
    })
    if (res.status) {
      hasPermission.value = res.data
    }
  } catch (error) {
    console.error('获取预分配人员失败:', error.message) // 更详细的错误信息
  }
}

const picList = ref([])
const imageList = ref([])

// 重置
const reset = () => {
  formData.value = {}
  console.log('reset', cacheFormData.value)
  formData.value = JSON.parse(JSON.stringify(cacheFormData.value))
}
// 保存巡查内容
const save = async () => {
  saveLoading.value = true
  try {
    const res = await savePatrolAlarmDetails({
      params: {
        ...formData.value,
        verified: formData.value.isVerified,
        invalidCause: formData.value.invalidCause,
        patrolDrop: formData.value.patrolDrop,
        patrolSpot: formData.value.patrolConditions,
        patrolValue: formData.value.patrolValue,
        coverRatio: Number(formData.value.coverRatio || 0),
        notes: formData.value.notes,
        datetime: formData.value.dateTime,
        alarmState: '2', // 告警状态
        picUrl: imageList.value
      }
    })
    if (res && res.status) {
      ElMessage({
        message: res.data,
        type: 'success'
      })
      fetchPatrolAlarmDetailInfo()
    } else {
      ElMessage({
        message: res.message,
        type: 'error'
      })
    }
    saveLoading.value = false
  } catch (error) {
    ElMessage({
      message: '获取获取告警详情信息失败',
      type: 'error'
    })
    saveLoading.value = false
  }
}

// 饲喂形态、病弱猪类型
const feedType = ref('')
const feedTypeOption = [
  {
    label: '干料',
    value: '干料'
  },
  {
    label: '湿拌料',
    value: '湿拌料'
  },
  {
    label: '水料',
    value: '水料'
  },
  {
    label: '干料',
    value: '干料'
  },
  {
    label: '发酵料',
    value: '发酵料'
  }
]
const illType = ref('')
const illTypeOption = [
  {
    label: '呼吸道',
    value: '呼吸道'
  },
  {
    label: '肢蹄病',
    value: '肢蹄病'
  },
  {
    label: '腹泻',
    value: '腹泻'
  },
  {
    label: '皮肤病',
    value: '皮肤病'
  },
  {
    label: '瘦弱',
    value: '瘦弱'
  }
]

// 添加水印
const addWatermark = async (base64Image) => {
  const img = new Image()
  img.src = base64Image
  await new Promise((resolve) => (img.onload = resolve))

  const canvas = document.createElement('canvas')
  const ctx = canvas.getContext('2d')

  canvas.width = img.width
  canvas.height = img.height

  // 绘制原始图片
  ctx.drawImage(img, 0, 0)

  // 添加多行水印文字（右下角）
  ctx.fillStyle = 'red' // 水印颜色
  ctx.font = '20px Arial'
  ctx.textAlign = 'right'
  ctx.textBaseline = 'bottom'

  const watermarkLines = [
    `养户:${formData.value.rearerName}`,
    `群号:${formData.value.flockNumber}`,
    `时间:${getCurrentDate()}`,
    `${formData.value.patrolItem == '3' ? `饲喂形态:${feedType.value}` : ''}`,
    `${formData.value.patrolItem == '3' ? `病弱猪类型:${illType.value}` : ''}`
  ]
  const lineHeight = 25 // 行高
  const startX = canvas.width - 20 // 右侧留白
  let startY = canvas.height - 20 // 底部留白

  watermarkLines.forEach((line) => {
    ctx.fillText(line, startX, startY)
    startY -= lineHeight
  })
  return canvas.toDataURL('image/png')
}

function base64ToFile(base64Image, filename) {
  // 步骤1: 去除 Base64 的 data URL 前缀
  const base64Data = base64Image.replace(/^data:image\/\w+;base64,/, '')

  // 步骤2: 解码 Base64 数据为二进制字符串
  const binaryString = atob(base64Data)

  // 步骤3: 转换为 Uint8Array
  const len = binaryString.length
  const bytes = new Uint8Array(len)
  for (let i = 0; i < len; i++) {
    bytes[i] = binaryString.charCodeAt(i)
  }

  // 步骤4: 创建 Blob 对象
  const blob = new Blob([bytes.buffer], { type: 'image/jpeg' }) // 根据实际图片类型修改 MIME 类型

  // 步骤5: 创建 File 对象
  const file = new File([blob], filename, { type: 'image/jpeg' })

  return file
}

onMounted(async () => {
  fetchPatrolAlarmDetailInfo()
  // 打开视频
  // showVideo()
  // 接收监听
  window.addEventListener('message', async (event) => {
    if (!event.data) {
      return
    }
    if (event.data.code == '100') {
      // 接收返回的可播放的列表
      list.value = event.data.msg
    } else if (event.data.code == '101') {
      const base64 = `data:image/*;base64,${event.data.msg}`
      // 添加水印
      const watermarkedBase64 = await addWatermark(base64)
      catchPicLoading.value = false
      const blob = base64ToFile(watermarkedBase64, 'test.jpg')
      const res = await uploadImage(blob)
      picList.value.push(`${import.meta.env.VITE_IMG_URL}${res.data[0]}`)
      imageList.value.push(res.data[0])
    } else if (event.data.code == '003') {
      ElMessage({
        message: event.data.msg,
        type: 'warning'
      })
    } else {
      console.log(event.data.msg)
    }
  })
})
</script>

<style scoped lang="scss">
.content {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  color: #fff;
  &-info {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    .form-item {
      width: 25%;
    }
  }
  .line {
    width: 100%;
    height: 3px;
    background-color: #2a4e7a;
    margin: 10px 0;
  }
  &-media {
    width: 100%;
    display: flex;
    &-left {
      width: 70%;
    }
    &-right {
      width: 30%;
    }
  }
  &-button {
    width: 100%;
    display: flex;
    justify-content: flex-end;
  }
}

.video {
  width: 100%;
  height: 600px;
  overflow: hidden;
}

.form {
  &-item {
    display: flex;
    align-items: flex-start;
    margin-bottom: 15px;

    > span {
      margin-right: 10px;
    }

    .el-select {
      width: 200px;
    }

    :deep(.el-date-editor.el-input, .el-date-editor.el-input__wrapper) {
      width: 200px;
    }

    .label {
      width: 100px;
    }
  }

  &-video {
    display: flex;
    flex-direction: column;
    margin-bottom: 10px;

    .label {
      font-weight: bold;
    }

    .btn-group {
      width: 500px;
      overflow-x: auto;
      display: flex;
      margin-bottom: 5px;
    }
  }

  &-image {
    display: flex;
    flex-direction: column;

    .label {
      font-weight: bold;
    }

    .imageBox {
      width: 500px;
      overflow-x: auto;
      display: flex;
      position: relative;
      align-items: flex-start;

      .delete {
        width: 10px;
        height: 10px;
      }

      &-item {
        margin-right: 10px;
      }
    }
  }
}

:deep(.el-button) {
  width: 150px;
}
</style>
